<?php

namespace App\Http\Controllers;

use App\Exceptions\DecryptDataErrorException;
use App\Exceptions\SessionKeyNotExistException;
use App\Exceptions\ShareExceedLimitsException;
use App\Exceptions\ShareNotAllowedException;
use App\Exceptions\ShareToSameGroupException;
use App\Http\Response\CreatedResponse;
use App\Models\PhonicsShare;
use App\Models\PhonicsStudent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PhonicsShareController extends Controller
{

    public function create(Request $request)
    {
        $this->validate($request, [
            'shareTicket' => 'required|string',
            'encryptedData' => 'required|string',
            'iv' => 'required|string',
            'socialCode' => 'required|string'
        ]);

        $studentId = intval($request->header("X-Authenticated-Userid"));

        $student = PhonicsStudent::find($studentId);
        if (empty($student) || $student->getSharePrivilege() == 0) {
            throw new ShareNotAllowedException();
        }

        if ($student->getShareCount() >= PhonicsStudent::SHARE_LIMITS) {
            throw new ShareExceedLimitsException();
        }
        $shareCounts = PhonicsShare::where('student_id', $studentId)->count();
        if ($shareCounts > PhonicsStudent::SHARE_LIMITS) {
            throw new ShareExceedLimitsException();
        }
        $socialCode = $request->input('socialCode');
        $shareTicket = $request->input('shareTicket');
        $encryptedData = $request->input('encryptedData');

        $appId = env('APP_ID');
        $cacheKey = "$appId:$socialCode";
        $cacheData = Cache::get($cacheKey);
        if (empty($cacheData)) {
            throw new SessionKeyNotExistException();
        }
        $cacheObj = json_decode($cacheData);
        if (empty($cacheObj->session_key)) {
            throw new SessionKeyNotExistException();
        }

        $sessionKey = $cacheObj->session_key;
        $iv = $request->input('iv');
        //decrypt data
        $encrypter = app('WxDecrypter');
        $result = $encrypter->decryptData($appId, $sessionKey, $encryptedData, $iv);

        if ($result['errorCode'] != 0) {
            throw new DecryptDataErrorException($result['errorCode']);
        }
        $data = $result['data'];
        //记录分享
        $dataObj = json_decode($data);
        $openGid = $dataObj->openGId;
        $sameGroupCount = PhonicsShare::where('student_id', $studentId)->where('open_gid', $openGid)->count();
        if ($sameGroupCount > 0) {
            throw new ShareToSameGroupException();
        }
        $bonus = 0;
        $studentSharedCounts = PhonicsShare::where('student_id', $studentId)->count();
        if ($studentSharedCounts === 0) {
            $bonus = rand(PhonicsShare::FIRST_SHARE_LOWER_LIMITS * 10, PhonicsShare::FIRST_SHARE_UPPER_LIMITS * 10) / 10;
        } else {
            $bonus = rand(PhonicsShare::OTHER_SHARE_LOWER_LIMITS * 10, PhonicsShare::OTHER_SHARE_UPPER_LIMITS * 10) / 10;
        }
        $share = new PhonicsShare();
        $share->setStudentId($studentId);
        $share->setShareTicket($shareTicket);
        $share->setOpenGid($openGid);
        $share->setBonus($bonus);
        $share->save();
        $student->setShareCount($student->getShareCount() + 1);
        $student->setBonus($student->getBonus() + $bonus);
        $student->setBonusLeft($student->getBonusLeft() + $bonus);
        $student->save();

        return new JsonResponse(['bonus' => $bonus], 201);
    }
}
